﻿var AccountCredential = function(constructors)  {

	var self = this;

	self.UserName = '';

	self.Password = '';

	self.Requesting = false;

	self.init = function() {
		var defaults = {
			UserName: '',
			Password: ''
		};

		$.extend(defaults, constructors);

		self.UserName = ko.observable(defaults.UserName);
		self.Password = ko.observable(defaults.Password);
		self.Requesting = ko.observable(false);
	}

	self.init();

	self.login = function() {
		if (self.Requesting()) return;
		self.Requesting(true);

		var loginUrl = app.baseUrl() + 'login';

		var credentialData = {
			UserName: self.UserName(),
			Password: self.Password()
		};

		$.ajax({
			url: loginUrl,
			type: 'POST',
			contentType: 'application/json',
			dataType: 'json',
			data: JSON.stringify(credentialData),
			async: false
		}).done(function(response) {
			try {
				console.info(response);
			}
			catch (ex) {

			}

			var defaultResponse = {
				Successful: false,
				Errors: []
			};

			$.extend(defaultResponse, response);

			if (!defaultResponse.Successful) {
				var message = '';

				if (defaultResponse.Errors.length > 0) {
					if (defaultResponse.Errors[0].Message != undefined) message  = defaultResponse.Errors[0].Message;
				}

				if ($.trim(message) == '') message = 'Failed to sign in using your acccount.';

				notification.shout({
					title: app.name() + ' - Login',
					text: message,
					image: 'warning'
				});
			}
			else {
				window.location.replace(app.baseUrl());
			}

		}).fail(function(response) {
			try {
				console.error(response);
			}
			catch (ex) {

			}

			notification.shout({
				title:  app.name() + ' - Login',
				text: 'An error occured while trying to sign in to your acccount.',
				image: 'error' 
			});
		}).always(function(response) {

		});

		self.Requesting(false);
	};

}

$(document).ready(function() {
	var credential = new AccountCredential();
	ko.applyBindings(credential);
});

